package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;

import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.Constant;
import com.recharge.common.util.TemplateUtils;

import com.recharge.core.entity.ProviderApiEntity;
import com.recharge.core.entity.ProviderCallbackEntity;
import com.recharge.core.mapper.ProviderApiMapper;
import com.recharge.core.mapper.ProviderCallbackMapper;
import com.recharge.domain.context.RedisMessageSerializer;
import com.recharge.domain.query.OrderStatusQueryDO;
import com.recharge.domain.query.ProviderApiQueryDO;
import com.recharge.domain.vo.*;
import com.recharge.service.*;
import com.recharge.service.httpInterFace.ProviderHTTPService;
import com.recharge.service.httpInterFace.ProviderInterFace;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.PostConstruct;
import javax.security.auth.callback.Callback;
import java.lang.management.RuntimeMXBean;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 上游供应商渠道API 服务实现类
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@Service
public class ProviderApiServiceImpl extends ServiceImpl<ProviderApiMapper, ProviderApiEntity> implements ProviderApiService, MessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    /**
     * 39
     */
    //private final int callbackThreadNumber = 50;

    private final int callbackThreadNumber = 50;

    volatile int maxThreadProvider = 0;

    @Autowired
    private ProviderCallbackMapper providerCallbackMapper;
    @Autowired
    private ProviderApiMapper providerApiMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProviderOrderService providerOrderService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CardVoucherService cardVoucherService;
    @Autowired
    private VoucherRecordService voucherRecordService;


    @Value("${node.name}")
    private Integer nodeName;

    @Value("${prefix.name}")
    private String prefixName;

    @Autowired
    private RedisTemplate<String, Object> redisMessageTemplate;

    private ThreadPoolExecutor callbackExecutor = null;

    private ThreadPoolExecutor maerchantSendExecutor = null;

    @PostConstruct
    public void init() {

        callbackExecutor =  new ThreadPoolExecutor(10, callbackThreadNumber,
                600,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(50000),
                new ThreadPoolExecutor.DiscardPolicy());

        maerchantSendExecutor = new ThreadPoolExecutor(10, callbackThreadNumber,
                600,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(50000),
                new ThreadPoolExecutor.DiscardPolicy());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultDO add(ProviderApiDO domain) {

        ProviderApiEntity entity = new ProviderApiEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        entity.setModifier(entity.getCreator());


        boolean res = false;
        try {
            res = this.save(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PROVIDER_ADD_SUPPLY_API_ERROR);
            logger.debug("error code：" + ErrorCode.PROVIDER_ADD_SUPPLY_API_ERROR.getCode() + " msg" + ErrorCode.PROVIDER_ADD_SUPPLY_API_ERROR.getMsg());
            return result;
        }
        return result;
    }

    @Override
    public ResultDO addCallback(ProviderCallbackDO domain) {

        ProviderCallbackEntity entity = new ProviderCallbackEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setNodeName(nodeName);
        int res = -1;
        try {
            res = providerCallbackMapper.insert(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (res <= 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CALLBACK_ADD_PROVIDER_ERROR);
            logger.debug("error code：" + ErrorCode.CALLBACK_ADD_PROVIDER_ERROR.getCode() + " msg" + ErrorCode.CALLBACK_ADD_PROVIDER_ERROR.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO updateCallback(String serialNumber, String voucherNo, String providerOrderNo, Integer status) {
        ResultDO result = new ResultSupport();
        ReceviceCallbackDO domain = new ReceviceCallbackDO();
        domain.setSerialNumber(serialNumber);
        domain.setVoucherNo(voucherNo);
        domain.setProviderOrderNo(providerOrderNo);
        domain.setStatus(status);
        logger.info("收到的上游回调信息" + domain);
        redisMessageTemplate.convertAndSend("callback:" + nodeName,  domain);
        return result;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        callbackExecutor.execute(()-> {
            {
                ReceviceCallbackDO domain = (ReceviceCallbackDO) RedisMessageSerializer.deserialize(message.getBody());
                int code = 0;
                int orderStatus = 0;
                int providerOrderStatus = 0;
                int cardStatus = Constant.CARDVOUCH_STATUS_VALID;
                if (domain.getStatus().intValue() == Constant.CALL_BACK_SUCCESS) {
                    orderStatus = Constant.RECHARGE_ORDER_STATUS_3;
                    providerOrderStatus = Constant.PROVIDER_ORDER_STATUS_2;
                    cardStatus = Constant.CARDVOUCH_STATUS_VERIFICATION;
                } else if (domain.getStatus().intValue() == Constant.CALL_BACK_FAIL) {
                    orderStatus = Constant.RECHARGE_ORDER_STATUS_4;
                    providerOrderStatus = Constant.PROVIDER_ORDER_STATUS_fail;
                    code = ErrorCode.API_ORDER_PROVIDER_FAIL.getCode();
                } else if (domain.getStatus().intValue() == Constant.CALL_BACK_NUKNOW) {
                    orderStatus = Constant.RECHARGE_ORDER_STATUS_7;
                    providerOrderStatus = Constant.PROVIDER_ORDER_STATUS_4;
                    code = ErrorCode.API_ORDER_STATUS_NUKNOW.getCode();
                } else if (domain.getStatus().intValue() == Constant.CALL_BACK_CARD_INVALID) {
                    orderStatus = Constant.RECHARGE_ORDER_STATUS_4;
                    providerOrderStatus = Constant.PROVIDER_ORDER_STATUS_fail;
                    cardStatus = Constant.CARDVOUCH_STATUS_INVALID;
                    code = ErrorCode.API_ORDER_STATUS_NUKNOW.getCode();
                }
                ResultDO result = new ResultSupport();
                ProviderCallbackEntity providerCallbackEntity = null;
                try {
                    providerCallbackEntity = providerCallbackMapper.selectOne(Wrappers.<ProviderCallbackEntity>lambdaQuery()
                            .eq(ProviderCallbackEntity::getSerialNumber, domain.getSerialNumber()));
                } catch (Exception e) {
                    e.printStackTrace();
                    result.setSuccess(false);
                    result.setErrorCode(ErrorCode.CALLBACK_EDIT_PROVIDER_ERROR);
                    logger.debug("error code：" + ErrorCode.CALLBACK_EDIT_PROVIDER_ERROR.getCode() + " msg" + ErrorCode.CALLBACK_EDIT_PROVIDER_ERROR.getMsg());
                }
                if(providerCallbackEntity != null) {
                    if (domain.getStatus() != 0) {
                        boolean isFinish = true;
                        do {
                            result = orderService.getRechagerStatusOrder(providerCallbackEntity.getOrderNo());
                            if (!result.isSuccess()) {
                                logger.info("订单不存在");
                                isFinish = false;
                                continue;
                            }
                            isFinish = true;
                            OrderDO order = (OrderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
                            order.setStatus(orderStatus);
                            order.setProcessTime(System.currentTimeMillis() - order.getCreateDate().getTime());
                            order.setProviderCallbackStatus(providerOrderStatus);
                            order.setModifiDate(Calendar.getInstance().getTime());

                            result = providerOrderService.updateProviderOrderStatus(order.getId(),
                                    domain.getProviderOrderNo(),
                                    providerOrderStatus,
                                    domain.getVoucherNo(),
                                    providerCallbackEntity.getSerialNumber());
                            if (!result.isSuccess()) {
                                logger.info("供应单更新失败");
                                return;
                            }
                            ProviderOrderDO providerOrderDO = (ProviderOrderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
                            if (providerOrderDO.getProviderMethod().intValue() == Constant.PROVIDER_METHOD_1) {
                                boolean isCardCallback = false;
                                logger.debug("供货方式为卡密转直充，开始更新卡密状态，写核销记录");
                                if(cardStatus == Constant.CARDVOUCH_STATUS_VERIFICATION) {
                                    order.setVoucherNo(providerOrderDO.getCardVoucherNo());
                                    result = cardVoucherService.editStatus(providerOrderDO.getCardVoucherNo(), cardStatus);
                                    isCardCallback = true;
                                } else if(cardStatus == Constant.CARDVOUCH_STATUS_VALID) {
                                    result = cardVoucherService.editStatus(providerOrderDO.getCardVoucherNo(), Constant.CARDVOUCH_STATUS_VALID);
                                } else if(cardStatus == Constant.CARDVOUCH_STATUS_INVALID) {
                                    result = cardVoucherService.editStatus(providerOrderDO.getCardVoucherNo(), cardStatus);
                                    isCardCallback = true;
                                }
                                if(isCardCallback) {
                                    CardVoucherDO cardVoucher = (CardVoucherDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
                                    VoucherRecordDO voucherRecordDO = new VoucherRecordDO();
                                    voucherRecordDO.setCardVoucherId(cardVoucher.getId());
                                    voucherRecordDO.setOrderId(order.getId());
                                    voucherRecordDO.setOrderNo(order.getOrderNo());
                                    voucherRecordDO.setProviderId(providerOrderDO.getProviderId());
                                    voucherRecordDO.setProviderOrderId(providerOrderDO.getId());
                                    voucherRecordDO.setProviderOrderNo(providerOrderDO.getProviderOrderNo());
                                    voucherRecordDO.setStatus(cardStatus);
                                    result = cardVoucherService.cardCallback(cardVoucher);
                                    voucherRecordDO.setReturnCode((String) result.getModel(ResultDO.FIRST_MODEL_KEY));
                                    voucherRecordService.add(voucherRecordDO);
                                }
                            } else {
                                order.setVoucherNo(domain.getVoucherNo());
                            }
                            result = orderService.editStatus(order);
                            if (!result.isSuccess()) {
                                logger.info("订单更新失败");
                                return;
                            }
                            maerchantSendExecutor.execute(new CallbackThread(order, domain, code));
                        } while(!isFinish);
                    }
                }
            }
        });

    }

    class CallbackThread implements Runnable {
        private OrderDO order;
        private ReceviceCallbackDO domain;
        private int code;
        private CallbackThread(OrderDO order, ReceviceCallbackDO domain, int code) {
            this.order = order;
            this.domain = domain;
            this.code = code;
        }
        public void run() {
            merchantService.callback(order.getMerchantSerialNumber(),
                    order.getOrderNo(),
                    order.getRechargeNumber(),
                    domain.getVoucherNo(),
                    code,
                    "",
                    order.getCallback());
        }
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultDO edit(ProviderApiDO domain) {

        ProviderApiEntity entity = new ProviderApiEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setModifiDate(Calendar.getInstance().getTime());

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PROVIDER_EDIT_SUPPLY_API_ERROR);
            logger.debug("error code：" + ErrorCode.PROVIDER_EDIT_SUPPLY_API_ERROR.getCode() + " msg" + ErrorCode.PROVIDER_EDIT_SUPPLY_API_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Override
    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        ProviderApiEntity entity = null;

        try {
            entity = this.getById(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        ProviderApiDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultDO remove(String id, String modifier) {
        ResultDO result = new ResultSupport();

        ProviderApiEntity entity = new ProviderApiEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setId(id);
        entity.setIsDelete(Constant.IS_DELETE);

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PROVIDER_DELETE_SUPPLY_API_ERROR);
            logger.debug("error code：" + ErrorCode.PROVIDER_DELETE_SUPPLY_API_ERROR.getCode() + " msg" + ErrorCode.PROVIDER_DELETE_SUPPLY_API_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public ResultDO removeByProviderId(String providerId, String modifier) {
        ResultDO result = new ResultSupport();

        ProviderApiEntity entity = new ProviderApiEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);

        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<ProviderApiEntity>lambdaQuery().eq(ProviderApiEntity::getProviderId, providerId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

//        //判断r的值是否小于0.如果小于0 就代表添加失败
//        if(!res) {
//            result.setSuccess(false);
//            result.setErrorCode(ErrorCode.PROVIDER_DELETE_SUPPLY_API_ERROR);
//            logger.debug("error code：" + ErrorCode.PROVIDER_DELETE_SUPPLY_API_ERROR.getCode() + " msg" + ErrorCode.PROVIDER_DELETE_SUPPLY_API_ERROR.getMsg());
//            return result;
//        }

        return result;
    }

//    @Override
//    public ResultDO getByProviderId(String providerId) {
//        ResultDO result = new ResultSupport();
//        ProviderApiEntity entity;
//        try {
//            entity = providerApiMapper.getOne(providerId);
//        } catch (Exception e) {
//            result.setSuccess(false);
//            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//            logger.debug("获取供货商提交信息失败 error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
//            return result;
//        }
//
//        ProviderApiDO domain = getDomain(entity);
//
//        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);
//
//        return result;
//    }

    @Override
    public ResultDO getByProviderNo(String providerNo) {
        ResultDO result = new ResultSupport();
        ProviderApiEntity entity;
        try {
            entity = providerApiMapper.selectOneByProviderNo(providerNo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("获取供货商提交信息失败 error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if (entity == null) {
            entity = new ProviderApiEntity();
            entity.setProviderNo(providerNo);
        }
        if (TemplateUtils.isEmpty(entity.getCallback())) {
            entity.setCallback(String.format("%s%s.html", prefixName, entity.getProviderNo()));
        }

        ProviderApiDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    public ResultDO find(ProviderApiQueryDO domain) {
        ProviderApiEntity entity = new ProviderApiEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);

        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        QueryWrapper<ProviderApiEntity> wrapper = new QueryWrapper<>(entity);
        Page<ProviderApiEntity> page = new Page<>(domain.getCurrentPage(), domain.getPageSize());
        IPage<ProviderApiEntity> iPage = null;

        try {
            iPage = baseMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<ProviderApiDO> doList = getDomainList(iPage.getRecords());
        PageDO<ProviderApiDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    @Override
    public ResultDO commitOrder(GoodsChannelDO domain) {
        ResultSupport result = new ResultSupport();
//        logger.debug("interface: "+domain.getInterfaceNum());
        if (domain.getInterfaceNum() == null || domain.getRequestUrl() == null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            result.setModel(ResultDO.FIRST_MODEL_KEY, Constant.BUSINESS_RECHARGE_RETURN_STATUS_FAIL);
            result.setModel(ResultDO.SECOND_MODEL_KEY, "供货商没有API提交接口");
            logger.debug(String.format("供货商(%s)没有API提交接口", domain.getProviderNo()));
            return result;
        }
        ProviderHTTPService httpObject = ProviderInterFace.getHTTPObject(domain.getInterfaceNum());
        if (httpObject == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            result.setModel(ResultDO.FIRST_MODEL_KEY, Constant.BUSINESS_RECHARGE_RETURN_STATUS_FAIL);
            result.setModel(ResultDO.SECOND_MODEL_KEY, "供货商没有API提交接口");
            logger.debug(String.format("没有查询到供货商(%s)API提交接口", domain.getUserId()));
            return result;
        }
        return httpObject.commitOrder(domain);
    }

    @Override
    public ResultDO backOrder(String providerNo, String paramStr, String bodyStr) {
        ResultDO result = new ResultSupport();
        // 获取供货商数据API信息
        ProviderApiEntity entity = null;
        try {
            entity = providerApiMapper.selectOneByProviderNo(providerNo);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        if (entity == null || entity.getInterfaceNum() == null) {
            result.setSuccess(false);
            result.setModel(ResultDO.FIRST_MODEL_KEY, "fail");
            logger.debug(String.format("获取供货商(%s)api信息失败", providerNo));
            return result;
        }
        ProviderHTTPService httpObject = ProviderInterFace.getHTTPObject(entity.getInterfaceNum());
        if (httpObject == null) {
            logger.debug(String.format("没有查询到供货商(%s)API接口", providerNo));
            result.setSuccess(false);
            result.setModel(ResultDO.FIRST_MODEL_KEY, "fail");
            return result;
        }
        ProviderApiDO domain = getDomain(entity);

        return httpObject.backOrder(domain, paramStr, bodyStr);
    }

    @Override
    public ResultDO queryBalance(ProviderApiDO providerApiDO) {
        ResultSupport result = new ResultSupport();
        if (providerApiDO.getInterfaceNum() == null || providerApiDO.getBalanceFindUrl() == null){
            result.setSuccess(false);
            logger.debug(String.format("没有查询到供货商(%s)API接口", providerApiDO.getUserId()));
            result.setModel(ResultDO.FIRST_MODEL_KEY, "查询失败");
            return result;
        }
        ProviderHTTPService httpObject = ProviderInterFace.getHTTPObject(providerApiDO.getInterfaceNum());
        if (httpObject == null) {
            result.setSuccess(false);
            logger.debug(String.format("没有查询到供货商(%s)API接口", providerApiDO.getUserId()));
            result.setModel(ResultDO.FIRST_MODEL_KEY, "查询失败");
            return result;
        }
        return httpObject.queryBalance(providerApiDO);
    }

    @Override
    public ResultDO queryOrder(OrderStatusQueryDO domain) {
        ResultSupport result = new ResultSupport();
        if (TemplateUtils.isEmpty(domain.getOrderFindUrl())) {
            result.setSuccess(false);
            result.setModel(ResultDO.THIRD_MODEL_KEY, "没有找到查询接口");
            logger.debug(String.format("没有查询到供货商(%s)API订单查询接口", domain.getUserId()));
            return result;
        }
        ProviderHTTPService httpObject = ProviderInterFace.getHTTPObject(domain.getInterfaceNum());
        if (httpObject == null) {
            result.setSuccess(false);
            result.setModel(ResultDO.THIRD_MODEL_KEY, "没有找到查询接口");
            logger.debug(String.format("没有查询到供货商(%s)API接口", domain.getUserId()));
            return result;
        }

        return httpObject.queryOrder(domain);
    }

    private ProviderApiDO getDomain(ProviderApiEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if (entity == null) return null;
        ProviderApiDO domain = new ProviderApiDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<ProviderApiDO> getDomainList(List<ProviderApiEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<ProviderApiDO> doList = new ArrayList<ProviderApiDO>();

        //判断传入的list的集合的size是否大于0
        if (list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for (ProviderApiEntity entity : list) {

                ProviderApiDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if (domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }

}
